package com.luoran.bartalks.core;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.entity.F4PageQueryInfo;
import com.luoran.bartalks.service.IF4Service;


/**
 * @author lifetime
 *
 */
@Controller
@RequestMapping("/f4")
public class F4Action {
	/**
	 * 每一页显示的条数
	 */
	public static final Integer PageSize = 10;
	/**
	 * 缓存列信息定义 f4-column-alias.properties
	 */
	private static final Properties AliasProp = new Properties();

	static {
		loadF4Config();
	}
	
	static void loadF4Config(){
		InputStream is = null;
		try {
			AliasProp.clear();
			is = F4Action.class.getResourceAsStream("/f4-column-alias.properties");
			AliasProp.load(is);
		} catch (IOException e) {
			System.err.println("f4-column-alias.properties load fail.");
			if (is != null) {
				try {
					is.close();
				} catch (IOException e1) {
				}
			}
		}
	}

	@Autowired
	private IF4Service service;
	
	@RequestMapping("/reload")
	@ResponseBody
	public String reload(){
		loadF4Config();
		return "reload success";
	}

	@RequestMapping(value = "/{table}/{params}", method = RequestMethod.GET)
	@ResponseBody
	public JSONObject handleRequest(@PathVariable String table, @PathVariable String params) {
		Map<String, Object> queryParams = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(params)) {
			JSONObject obj = JSONObject.parseObject(params);
			queryParams.putAll(obj);
		}
		int page = 1;// 当前页码
		if (queryParams.get("page") != null) {
			page = (Integer) queryParams.get("page");
			queryParams.remove("page");
		}
		F4PageQueryInfo f4PageQueryInfo = new F4PageQueryInfo();
		f4PageQueryInfo.setOrderBy("");
		f4PageQueryInfo.setPageNumber(page);
		f4PageQueryInfo.setPageSize(PageSize);
		f4PageQueryInfo.setQueryParams(queryParams);
		PageQuery<Map<String, Object>> result = service.f4Query(table, f4PageQueryInfo);
		JSONObject obj = new JSONObject();
		obj.put("total", result.getTotalRow());
		obj.put("page", page);
		obj.put("pageSize", PageSize);
		JSONArray heads = buildHead(AliasProp.getProperty(table + ".keys"), AliasProp.getProperty(table + ".columns"), AliasProp.getProperty(table + ".isShow"));
		obj.put("heads", heads);
		JSONArray arr = new JSONArray();
		if (result.getList() != null) {
			for (int i = 0, k = result.getList().size(); i < k; i++) {
				Map<String, Object> u = result.getList().get(i);
				arr.add(u);
			}
		}
		obj.put("rows", arr);
		obj.put("pager", rebuildPageInfo((int) result.getTotalRow(), page));
		return obj;
	}

	static JSONArray buildHead(String headKeyString, String headAliasString, String isShows) {
		String[] keys = headKeyString.split(",");
		String[] alias = headAliasString.split(",");
		String[] shows = isShows.split(",");
		if (keys.length != alias.length) {
			throw new RuntimeException("key 与 别名的数量不一致");
		}
		JSONArray heads = new JSONArray();
		for (int i = 0; i < keys.length; i++) {
			JSONObject o = new JSONObject();
			o.put("key", keys[i]);
			o.put("text", alias[i]);
			if (shows.length > i) {
				o.put("isShow", Boolean.valueOf(shows[i]));
			}
			heads.add(o);
		}
		return heads;
	}

	/**
	 * @param total
	 *            数据的总条数
	 * @param pageNum
	 *            当前的页码
	 * @param pageInfo
	 *            分页对象
	 */
	JSONObject rebuildPageInfo(int total, Integer pageNum) {
		JSONObject pageInfo = new JSONObject();
		int allPageSize = (int) (total / PageSize) + (total % PageSize == 0 ? 0 : 1);
		JSONArray arr = new JSONArray();
		if (allPageSize > 6) {
			if (pageNum >= 5) {
				// << , ... , 3 , 4 , 5 , ... , >>
				JSONObject index = new JSONObject();
				index.put("text", "«");
				if (pageNum == 1) {
					index.put("class", "disabled");
				}
				arr.add(index);

				index = new JSONObject();
				index.put("text", 1);
				arr.add(index);

				index = new JSONObject();
				index.put("text", "...");
				index.put("class", "disabled");
				arr.add(index);

				index = new JSONObject();
				index.put("text", pageNum - 1);
				arr.add(index);

				index = new JSONObject();
				index.put("text", pageNum);
				index.put("class", "active");
				arr.add(index);

				if (pageNum + 1 <= allPageSize) {
					index = new JSONObject();
					index.put("text", pageNum + 1);
					arr.add(index);

					if (pageNum + 3 <= allPageSize) {
						index = new JSONObject();
						index.put("text", "...");
						index.put("class", "disabled");
						arr.add(index);
					}
					if (pageNum + 1 != allPageSize) {
						index = new JSONObject();
						index.put("text", allPageSize);
						arr.add(index);
					}
				}

				index = new JSONObject();
				index.put("text", "»");
				if (pageNum == allPageSize) {
					index.put("class", "disabled");
				}
				arr.add(index);
				pageInfo.put("pageIndexs", arr);
			} else {
				JSONObject index = new JSONObject();
				index.put("text", "«");
				if (pageNum == 1) {
					index.put("class", "disabled");
				}
				arr.add(index);
				for (int i = 1; i <= 5; i++) {
					index = new JSONObject();
					index.put("text", i);
					if (pageNum == i) {
						index.put("class", "active");
					}
					arr.add(index);
				}
				index = new JSONObject();
				index.put("text", "...");
				arr.add(index);

				index = new JSONObject();
				index.put("text", allPageSize);
				arr.add(index);

				index = new JSONObject();
				index.put("text", "»");
				if (pageNum == allPageSize) {
					index.put("class", "disabled");
				}
				arr.add(index);
				pageInfo.put("pageIndexs", arr);
			}
		} else {
			JSONObject index = new JSONObject();
			index.put("text", "«");
			if (pageNum == 1) {
				index.put("class", "disabled");
			}
			arr.add(index);
			for (int i = 1; i <= allPageSize; i++) {
				index = new JSONObject();
				index.put("text", i);
				if (pageNum == i) {
					index.put("class", "active");
				}
				arr.add(index);
			}
			index = new JSONObject();
			index.put("text", "»");
			if (pageNum == allPageSize) {
				index.put("class", "disabled");
			}
			arr.add(index);
			pageInfo.put("pageIndexs", arr);
		}
		return pageInfo;
	}

}

